package cn.jskyme.mail;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;

/**
 * @author jskyme http://blog.csdn.net/chjttony/article/details/6005594
 */
public class MailExamle {

	public void mailSend() throws MessagingException, IOException {
		Properties props = new Properties();
		// 存储接收邮件服务器使用的协议，这里以POP3为例
		props.setProperty("mail.store.protocol", "pop3");
		// 设置接收邮件服务器的地址，这里还是以网易163为例
		props.setProperty("mail.pop3.host", "pop3.163.com");
		// 根据属性新建一个邮件会话.
		Session session = Session.getInstance(props);
		// 从会话对象中获得POP3协议的Store对象
		Store store = session.getStore("pop3");
		// 如果需要查看接收邮件的详细信息，需要设置Debug标志
		session.setDebug(false);
		// 连接邮件服务器 -----------------------------------
		store.connect("pop3.163.com", "username", "password");
		// 获取邮件服务器的收件箱
		Folder folder = store.getFolder("INBOX");
		// 以只读权限打开收件箱
		folder.open(Folder.READ_ONLY);
		// --------------------------------------------
		// 获取收件箱中的邮件，也可以使用getMessage(int 邮件的编号)来获取具体某一封邮件
		Message message[] = folder.getMessages();
		for (int x = 0, y = message.length; x < y; x++) {
			// 获取邮件具体信息
			// ---------------------------------------------------
			Multipart multipart = (Multipart) message[x].getContent();
			for (int i = 0, n = multipart.getCount(); i < n; i++) {
				Part part = multipart.getBodyPart(i);
				String disposition = part.getDisposition();
				if ((disposition != null)
						&& (disposition.equals(Part.ATTACHMENT) || (disposition
								.equals(Part.INLINE)))) {
					saveFile(part.getFileName(), part.getInputStream());
				}
			}
			message[x].setFlag(Flags.Flag.ANSWERED,true); 
			message[x].saveChanges();
			
			//创建搜索条件  
			SearchTerm st=new OrTerm (new FromStringTerm("test1@163.com"), new FromStringTerm("test2@163.com"));  
			//搜索邮件  
			Message[] msgs=folder.search(st); 
			
			//创建搜索条件  
			SearchTerm st1=new AndTerm(new FromStringTerm("test1@163.com"),  
			new ReceivedDateTerm(ComparisonTerm.EQ,new Date()));  
			//搜索邮件  
			Message [] msg1s=folder.search(st1);
		}
		// 关闭连接
		folder.close(false);
		store.close();
//
		folder.open(Folder.READ_WRITE);  
		//设置标记  
	
	}

	private void saveFile(String fileName, InputStream inputStream) {
		

	}

	public void mail() throws NoSuchProviderException {

	}
}
